import Taro from '@tarojs/taro'
import { View, Text, Navigator } from '@tarojs/components'
import { AtSearchBar, AtActivityIndicator, AtModal, AtModalContent, AtModalAction } from 'taro-ui'
import { connect } from '@tarojs/redux'

import { getPartner, saleGoods } from '../../api/partner'
import { showToast, getUpdatePage } from '../../utils'
import { ListLoading } from '../../components/loading'
import { setPartnerInfo } from '../../actions/partner'

import './index.less'

@connect(() => ({}), { setPartnerInfo })
class Partner extends Taro.Component {
  config = {
    navigationBarTitleText: '我的合伙人'
  }

  state = {
    params: {
      pageNum: 1,
      pageSize: 12,
      key: 1,
      value: ''
    },
    partnerList: [],
    isDone: false,
    isShowModal: false,
    modalForm: {
      targetPartnerId: '',
      actualAmount: '',
      soldAmount: '',
      levelId: ''
    },
    isAdd: true,
    isFocus: false
  }

  async componentWillMount() {
    const levelId = await Taro.getStorage({key: 'levelId'})

    if (levelId.data === 4) {
      this.setState({
        isAdd: false
      })
    }
  }

  getData = async () => {
    const res = await getPartner(this.state.params)

    this.setState(({ partnerList }) => ({
      partnerList: partnerList.concat(res.data)
    }), () => {
      if (this.state.partnerList.length === res.rowCount) {
        this.setState({
          isDone: true
        })
      }
    })
  }

  componentDidMount() {
    this.setState({
      params: {
        ...this.state.params,
        value: this.$router.params.value
      }
    }, () => {
      this.getData()
    })
  }

  componentDidShow() {
    getUpdatePage(() => {
      this.setState({
        partnerList: [],
        isDone: false,
        params: {
          ...this.state.params,
          pageNum: 1
        }
      }, () => {
        this.getData()
      })
    })
  }

  onReachBottom(){
    if (this.state.isDone) return

    const { pageNum } = this.state.params

    this.setState({
      params: {
        ...this.state.params,
        pageNum: pageNum + 1
      }
    }, () => {
      this.getData()
    })
  }

  call = phone => {
    Taro.makePhoneCall({
      phoneNumber: phone
    })
  }

  getClassName = levelId => {
    switch(levelId) {
      case 2:
        return 'city-partner'
      case 3:
        return 'senior-partner'
      case 4:
        return 'partner'
    }
  }

  handleInput = (key, ev) => {
    this.setState({
      modalForm: {
        ...this.state.modalForm,
        [key]: ev.target.value
      }
    })
  }

  showModal = (id, levelId) => {
    this.setState({
      isShowModal: true,
      modalForm: {
        ...this.state.modalForm,
        targetPartnerId: id,
        levelId
      }
    })
  }

  onModalClose = () => {
    this.setState({
      isShowModal: false,
      modalForm: {
        targetPartnerId: '',
        actualAmount: '',
        soldAmount: '',
        levelId: ''
      }
    })
  }

  handleSubmit = async () => {
    const { targetPartnerId, actualAmount, soldAmount } = this.state.modalForm
    const reg = /^[1-9]\d{0,5}$/

    if (actualAmount === '') {
      showToast('请填写实收金额')

      return
    }

    if (soldAmount === '') {
      showToast('请填写调货金额')

      return
    }

    if (!reg.test(actualAmount)) {
      showToast('实收金额有误')

      return
    }

    if (!reg.test(soldAmount)) {
      showToast('调货金额有误')

      return
    }
    
    const res = await saleGoods(this.state.modalForm)
    const { partnerList } = this.state

    if (res.code == 1) {
      for (let item of partnerList) {
        if (item.id === targetPartnerId) {
          item.accountBalance += +soldAmount
          item.goodsAmount += +soldAmount

          this.setState({ partnerList })

          break
        }
      }
    }

    showToast(res.message)
    this.onModalClose()
  }

  toInfo = info => {
    this.props.setPartnerInfo(info)

    Taro.navigateTo({
      url: 'baseInfo'
    })
  }

  toSearch = () => {
    if (!this.state.params.value) {
      showToast('请输入要搜索的内容！')

      return
    }

    if (this.$router.params.value) {
      this.setState({
        partnerList: [],
        isDone: false,
        params: {
          ...this.state.params,
          pageNum: 1
        },
      }, () => {
        this.getData()
      })
    } else {
      Taro.navigateTo({
        url: 'index?value=' + this.state.params.value
      })
  
      this.setState({
        params: {
          ...this.state.params,
          value: ''
        }
      })
    }
  }

  handleChange = val => {
    this.setState({
      params: {
        ...this.state.params,
        value: val.trim()
      }
    })
  }

  render() {
    const { partnerList, isDone, isShowModal, modalForm, isAdd, params, isFocus } = this.state

    return (
      <View className="page" style={{ paddingBottom: isAdd ? '48Px' : 0 }}>
        <AtSearchBar
          placeholder="搜索合伙人姓名/手机号"
          value={ params.value }
          onChange={ this.handleChange }
          onActionClick={ this.toSearch }
          onFocus={ () => this.setState({ isFocus: true }) }
          onBlur={ () => this.setState({ isFocus: false }) }
          onConfirm={ this.toSearch }
        />
        {
          isFocus
          ? <View className="search-mask" />
          : null
        }
        <View className="partner-list" style={{ paddingLeft: '15Px' }}>
          {
            partnerList.map(item => (
              <View className="item" key={ item.id }>
                <View className="info" onClick={ this.toInfo.bind(this, item) }>
                  <View className="name">
                    <Text>{ item.name }</Text>
                    <Text>{ item.mobile }</Text>
                    <View className={ `tag ${ this.getClassName(item.levelId) }` }>{ item.levelStr }</View>
                  </View>
                  <Text>余额：{ item.accountBalance }</Text>
                </View>
                <View className="right">
                  <View className="icon" onClick={ this.showModal.bind(this, item.id, item.levelId) }>
                    <Image src={ require('../../assets/images/diaohuo.png') } />
                    <View>调货</View>
                  </View>
                  <View className="line"></View>
                  <View className="icon" onClick={ this.call.bind(this, item.mobile) }>
                    <Image src={ require('../../assets/images/dial.png') } />
                    <View>电话</View>
                  </View>
                </View>
              </View>
            ))
          }
        </View>
        <ListLoading isDone={ isDone } data={ partnerList } />
        {
          isAdd
          ? <Navigator url="/pages/partner/addPartner" className="add-btn">新增</Navigator>
          : null
        }
        <AtModal isOpened={ isShowModal } onClose={ this.onModalClose }>
          <AtModalContent>
            <View className="modal-input">
              <Text>实收金额：</Text><Input type="number" value={ modalForm.actualAmount } onInput={ this.handleInput.bind(this, 'actualAmount')} />
            </View>
            <View className="modal-input">
              <Text>调货金额：</Text><Input type="number" value={ modalForm.soldAmount } onInput={ this.handleInput.bind(this, 'soldAmount')} />
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button onClick={ this.onModalClose }>取消</Button>
            <Button onClick={ this.handleSubmit }>确定</Button>
          </AtModalAction>
        </AtModal>
      </View>
    )
  }
}

export default Partner